package com.lk.sys.service.impl;

import com.lk.sys.common.annotation.RequiredLog;
import com.lk.sys.common.vo.PageObject;
import com.lk.sys.common.vo.SysUserDeptVo;
import com.lk.sys.dao.SysUserDao;
import com.lk.sys.dao.SysUserRoleDao;
import com.lk.sys.entity.SysUsr;
import com.lk.sys.service.SysUserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
//import sun.jvm.hotspot.debugger.Page;

//import javax.swing.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Transactional(timeout = 30,
               readOnly = false,
               isolation = Isolation.READ_COMMITTED,
               rollbackFor = Throwable.class,
               propagation = Propagation.REQUIRED)
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;


    /**
     * 用户添加界面，save按钮更新用户信息以及用户对应的角色信息
     * @author Lukang
     * @date 2022/1/7 下午9:48
     * @param entity
     * @param roleIds
     * @return int
     */
    @RequiredLog(operation = "更新数据")
    @Override
    public int updateObject(SysUsr entity, Integer[] roleIds) {
        //1.参数校验
        if (entity  == null) throw new IllegalArgumentException("角色对象不能为空");
        if (StringUtils.isEmpty(entity.getUsername())) throw new IllegalArgumentException("用户名称不能为空");
        if (StringUtils.isEmpty(entity.getMobile())) throw new IllegalArgumentException("电话不能为空");
        if (roleIds==null || roleIds.length == 0) throw new IllegalArgumentException("用户权限不能为空");
        //2.参数更新
        //2.1用户信息更新
        int rows = sysUserDao.updateObject(entity);
        //2.2基于用户id删除用户对应的角色信息
        sysUserRoleDao.deleteRoleIdByUserId(entity.getId());
        //2.3更新用户对应的角色信息
        sysUserRoleDao.inserObjects(entity.getId(), roleIds);
        return rows;
    }

    /**
     * 通过用户id查询用户相关信息和用户角色信息，并封装到map集合中
     * @author Lukang
     * @date 2022/1/6 下午10:06
     * @param id
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @RequiredLog(operation = "修改数据")
    @Override
    public Map<String, Object> findObjectById(Long id) {
        //1.参数校验
        if(id == null || id < 0)
            throw new IllegalArgumentException("参数不合法");
        //2.业务查询
        SysUserDeptVo user = sysUserDao.findObjectById(id);
        if (user == null)
            throw new IllegalArgumentException("此用户已不存在");
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(id);
        //3.封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roleIds", roleIds);
        return map;
    }

    /**
     * 添加界面保存数据接口实现方法
     * @author Lukang
     * @date 2022/1/5 下午10:07
     * @param entity
     * @param roleIds
     * @return int
     */
    @Override
    public int saveObject(SysUsr entity, Integer[] roleIds) {
        //1参数校验
        if (entity == null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if(StringUtils.isEmpty(entity.getPassword()))
            throw new IllegalArgumentException("密码不能为空");
        if (roleIds == null || roleIds.length ==0)
            throw new IllegalArgumentException("至少要为用户分配一个角色");
        //2保存用户自身信息
        //2.1对密码进行加密
        //2.1.1获取密码
        String source = entity.getPassword();
        //2.1.2获取盐值
        String salt = UUID.randomUUID().toString();
        //2.1.3 对密码加密
        SimpleHash simpleHash = new SimpleHash("MD5", source, salt, 1);
        //2.1.4 将盐值和加密后的密码存储到对象中
        entity.setSalt(salt);
        //将密码转化程16为进行存储，因为加盐后的密码会很长
        entity.setPassword(simpleHash.toHex());
        int rows = sysUserDao.insertObject(entity);
        //3 保存用户角色关系数据
        sysUserRoleDao.inserObjects(entity.getId(), roleIds);
        return rows;
    }

    /**
     * 用户禁用启用接口
     * @author Lukang
     * @date 2022/1/2 下午3:20
     * @param id
     * @param valid
     * @return int
     */
    @RequiredLog(operation = "禁用/启用")
    @Override
    public int validById(Long id, Integer valid) {

        //1。参数校验
        if (id == null || id < 1) throw new IllegalArgumentException("id值不正确 id = " + id);
        if(valid!=1 && valid!=0) throw new IllegalArgumentException("参数不合法， valid = " + valid);
        //2。状态更新
        int rows = sysUserDao.validById(id, valid, "admin");
        if (rows == 0 ) throw new RuntimeException("此记录可能已被删除");
        //3。返回更新的行数
        return rows;
    }
    @Transactional(readOnly = true)
    @RequiredLog(operation = "查询数据")
    @Override
    public PageObject<SysUserDeptVo> findPageObjects(String username, Long pageCurrent) {
        String threadName = Thread.currentThread().getName();
        System.out.println("findPageObjects-->"+threadName);
        //1。参数校验
        if(pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("当前页码值无效");
        //2。查询总记录数
        long rowCount = sysUserDao.getRowCount(username);
        if (rowCount == 0)
            throw new RuntimeException("当前无记录");
        //3。查询当前页记录
        int pageSize = 5;
        long startIndex = (pageCurrent - 1) * pageSize;
        List<SysUserDeptVo> records = sysUserDao.findPageObjects(username, startIndex, pageSize);
        //4。返回pageObject
        return new PageObject<>(records, rowCount, pageSize, pageCurrent);
    }
}
